package com.novel.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

public class HttpUtils {

    public static String sendRequest(String urlParam,String requestType) {
        HttpURLConnection con = null;  

        BufferedReader buffer = null; 
        StringBuffer resultBuffer = null;  

        try {
            URL url = new URL(urlParam); 
            //得到连接对象
            con = (HttpURLConnection) url.openConnection(); 
            //设置请求类型
            con.setRequestMethod(requestType);  
            //设置请求需要返回的数据类型和字符集类型
            con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");  
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }

        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    
    public static JSONObject httpPostWithJson(Object jsonObj,String url){
        JSONObject ret = null;
        HttpClient httpClient =new DefaultHttpClient();
        HttpPost post = null;
        try {
            // 设置超时时间
            RequestConfig defaultRequestConfig = RequestConfig.custom()
            	    .setSocketTimeout(2000)
            	    .setConnectTimeout(2000)
            	    .build();
            
            post = new HttpPost(url);
            post.setConfig(defaultRequestConfig);
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            String jsonstr = JSON.toJSONString(jsonObj);
            // 构建消息实体
            StringEntity entity = new StringEntity(jsonstr, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);

            HttpResponse response = httpClient.execute(post);

            String line=null;
            StringBuffer entityStringBuilder=new StringBuffer();
            try {
                BufferedReader b = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"),8*1024);
                while ((line=b.readLine())!=null) {
                    entityStringBuilder.append(line+"\n");
                }
                String str = entityStringBuilder.toString();
                ret = JSONObject.parseObject(str);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            ret = null;
        }finally{
            if(post != null){
                post.releaseConnection();
            }
        }
        return ret;
    }
    
    
   /* public static void main(String[] args) {

        String url ="https://www.17k.com/chapter/1352782/22172276.html";
        String content = sendRequest(url,"GET");
        int i=0;
        i++;
        System.out.println(content+i);
    }*/
}
